 //
//  Communication.m
//  Jyxt
//
//  Created by 刘日 on 17/5/18.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "Communication.h"
#import "FreeCtrlCom.h"
#import "LoadDelegateCom.h"
#import "LemonMixView.h"

@interface Communication()

@property (nonatomic , strong)FreeCtrlCom *FreeCtrl;
@property (nonatomic , strong)LoadDelegateCom *LoadDelegate;

@property (nonatomic , strong)LemonMixView *mixView;
@property (nonatomic , strong)WKWebView *webView;

@end

@implementation Communication

- (instancetype)initWithMixView: (LemonMixView *)mixView webView:(WKWebView *)webView{
    if (self = [super init]) {
        self.mixView = mixView;
        self.webView = webView;
    }
    return self;
}

- (FreeCtrlCom *)FreeCtrl{
    if (!_FreeCtrl) {
        _FreeCtrl = [[FreeCtrlCom alloc] initWithMixView: _mixView webView: _webView];
    }
    return _FreeCtrl;
}

- (LoadDelegateCom *)LoadDelegate{
    if (!_LoadDelegate) {
        _LoadDelegate = [[LoadDelegateCom alloc] initWithMixView: _mixView webView: _webView];
    }
    return _LoadDelegate;
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    NSLog(@"default TEXT : %@" , defaultText);
    NSData *jsonData = [defaultText dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *info = [NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingMutableContainers error: nil];
    for (LM_MIX_ON_RECEIVE_JS_MSG msg in self.mixView.on.onReceiveJSMsgArr) {
        msg(self.mixView,info);
    }
    @try {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [[self valueForKey: info[@"clazz"]] performSelector: NSSelectorFromString([NSString stringWithFormat: @"%@:" , info[@"method"]]) withObject: info[@"data"]];
#pragma clang diagnostic pop
    } @catch (NSException *exception) {
        NSLog(@"LemonMix提示：无法找到指定的方法！%@" , exception);
    } @finally {
        
    }
    completionHandler(@"LemonMix");
}

@end
